package com.xing.msmServer.controller;

import com.xing.commonutils.R;
import com.xing.msmServer.service.MSMService;
import com.xing.msmServer.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务
 *
 * @author: xingfuhao
 * @create: 2022-03-24 22:28
 */

@RestController
@Api(description = "短信服务")
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MSMController {

    @Autowired
    private MSMService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){

        //从redis中获取验证码，如果获取到就直接返回
        String code = redisTemplate.opsForValue().get(phone);
        System.out.println("code=====>"+code);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }

        //生成随机值，传递给阿里云进行发送
        code = RandomUtil.getFourdf();
        Map<Object, Object> param = new HashMap<>();
        param.put("code", code);

        //调用service发送短信的方法
       boolean isSend = msmService.send(param,phone);
       if(isSend){
           //发送成功，把发送成功的验证码放到redis里面
           redisTemplate.opsForValue().set(phone,code,10, TimeUnit.MINUTES);
           return R.ok();
       }else {
           return R.error().message("短信发送失败");
       }

    }


}
